package org.teachertools.web.jsonview;

import java.io.PrintWriter;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.web.servlet.View;

// TODO Refactor Json View Handler
@Configurable
public class JsonView implements View {

    // private static final String JSON_CONTENT_TYPE = "text/json; charset=UTF-8";
    private static final String JSON_CONTENT_TYPE = "text/html; charset=ISO-8859-1";

    @Resource
    private JsonMarshaller marshaller;

    public JsonView() {
        super();
    }

    public String getContentType() {
        return JSON_CONTENT_TYPE;
    }

    @SuppressWarnings("unchecked")
    public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Validate.isTrue(model.size() == 1, "There should only be one item in the returning model");

        Object data = model.values().iterator().next();
        PrintWriter writer = response.getWriter();
        // even though the following method is "toXML" XStream is configured
        // to use Jettison to output JSON instead
        this.marshaller.marshall(writer, data);
    }

    public void setMarshaller(JsonMarshaller marshaller) {
        this.marshaller = marshaller;
    }
}
